package com.zhangx.mq.demo.rabbit.receiver;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

/**
 * @ClassName Receiver
 * @Description 手动接收确认
 * @Author zhangx
 * @Date 2021/4/23 9:13
 **/
@Slf4j
@Component
public class Receiver implements ChannelAwareMessageListener {
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        String msg = new String(message.getBody());

        log.info("Receiver收到消息:{}",msg);
        try {

//        这个消息id 没有重复消费
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            log.info("消息id={}消费",message.getMessageProperties().getDeliveryTag());
        }catch (Exception e){
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            log.info("消息id={}消费异常，请求重发",message.getMessageProperties().getDeliveryTag());
        }

    }
}
